import json

from django_redis import get_redis_connection


class RedisUtils:
    def __init__(self, cache='default'):
        self.redis_conn = get_redis_connection(cache)

    def write_value_as_string(self, key, value, ex=None):
        if ex:
            return self.set_ex(key, ex, json.dumps(value))
        return self.set(key, json.dumps(value))

    def read_value_to_object(self, key):
        value = self.redis_conn.get(key)
        if value:
            return json.loads(value)

    def set(self, key, value):
        return self.redis_conn.set(key, value)

    def set_ex(self, key, timeout, value):
        return self.redis_conn.setex(key, time=timeout, value=value)

    def delete(self, key):
        return self.redis_conn.delete(key)
